'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/pages/writeoff/kh/writeoff_edit 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_,
			$
		} = util;
		let {
			uid,
			order_id,
			status
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		// return res
		
		console.log("核销参数",data)
		
		console.log('开始status',status)
		
		if(status === 1) {
			status = 2
		}else if(status === 2){
			status = 3
		}
		
		
		console.log("最终status",status)
		let order_data = await vk.baseDao.findByWhereJson({
			dbName: "daoju_order",
			whereJson: {
				out_trade_no: order_id
			},

		})
		let order_status = order_data?.status || 0
		console.log('order_status', order_status)
		if (!(order_status == 1 || order_status == 2)) {
			return {
				msg: "此订单状态不可核销",
				code: -1
			}
		}

		res.num = await vk.baseDao.update({
			dbName: "daoju_order", // 表名
			whereJson: { // 条件
				out_trade_no: order_id,
			},
			dataJson: {
				status:status,
				write_time:new Date().getTime(),
				write_user_id:uid
			}
		});
		
		
		if(status === 3){
			let {product_list} = order_data
			
			for(let item of product_list){
				console.log('item',item)
				await vk.baseDao.update({
				  dbName: "daoju_merchandise", // 表名
				  whereJson: { // 条件
				    _id: item.merchandise_id,
				  },
				  dataJson: { // 需要修改的数据
				    inventory: _.inc(item.number)
				  }
				});
			}
		}
		
		if (res.num >= 1) {

			res.msg = '核销成功'

			return res;
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}